﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using SymbolEditor.WpfLibrary.Helper;
using System.IO;
using SymbolEditor.WpfLibrary.Serialize;
using System.Net;

namespace SymbolEditor.WpfLibrary
{
    public delegate void StrongSymbolClickEventHandler(string LibPath,string XamlName,string SymbolName);

    /// <summary>
    /// UserControl2.xaml 的交互逻辑
    /// </summary>
    public partial class UCMainWindow : UserControl
    {
        public UCMainWindow()
        {
            InitializeComponent();
            InitializeSymbolList();
            InitializeContextMenu();
        }

        

        private string SymbolLibDir = @"\SymbolLib\";

        private ContextMenu graphicContextMenu = null;

        public event StrongSymbolClickEventHandler OnStrongSymbolClicked = null;

        private void InitializeContextMenu()
        {
            graphicContextMenu = new ContextMenu();

            MenuItem editSymbolItem = new MenuItem();
            editSymbolItem.Header = "Edit It";
            editSymbolItem.Click += new RoutedEventHandler(editSymbolItem_Click);

            MenuItem strongSymbolItem = new MenuItem();
            strongSymbolItem.Header = "Generate Strong Symbol";
            strongSymbolItem.Click += new RoutedEventHandler(strongSymbolItem_Click);

            graphicContextMenu.Items.Add(editSymbolItem);
            graphicContextMenu.Items.Add(strongSymbolItem);
            graphicContextMenu.StaysOpen = true;
            graphicContextMenu.Opened += new RoutedEventHandler(graphicContextMenu_Opened);
            graphicContextMenu.Closed += new RoutedEventHandler(graphicContextMenuContextMenu_Closed);
        }

        void strongSymbolItem_Click(object sender, RoutedEventArgs e)
        {
            if (OnStrongSymbolClicked != null && currentGraphic != null)
            {
                string libdir = ArcServerClientHelper.GetThisAssemblyDirectory() + "\\" + SymbolLibDir;
                OnStrongSymbolClicked(libdir,
                                        currentGraphic.Attributes[ArcServerClientHelper.STR_GRAPHIC_ATT_SET].ToString(),
                                       currentGraphic.Attributes[ArcServerClientHelper.STR_GRAPHIC_ATT_KEY].ToString());
            }
        }

        void editSymbolItem_Click(object sender, RoutedEventArgs e)
        {
            dlgSymbolEditor dlg = new dlgSymbolEditor();
            Graphic graphicCopy = ArcServerClientHelper.Copy(currentGraphic);
            dlg.Graphic = graphicCopy;
            dlg.RDHander = serializer.XmalRDHander;
            dlg.RDFooter = serializer.XmalRDFooter;
            //dlg.XamlSymbol = serializer.XamlSymbols[e.Graphic.Attributes["KEY"].ToString()];
            dlg.ShowDialog();
        }

        void graphicContextMenuContextMenu_Closed(object sender, RoutedEventArgs e)
        {

        }

        void graphicContextMenu_Opened(object sender, RoutedEventArgs e)
        {

        }

        private class CustomItem
        {
            public string DisplayText;
            public string InnerText;

            public CustomItem(string DisplayText, string InnerText)
            {
                this.DisplayText = DisplayText;
                this.InnerText = InnerText;
            }

            public override string ToString()
            {
                return DisplayText;
            }
        }

        private void InitializeSymbolList()
        {
            string[] xmalfiles = getXmalFiles();
            int pos = 1;
            if (xmalfiles != null)
                foreach (string file in xmalfiles)
                {
                    CustomItem item = new CustomItem(System.IO.Path.GetFileNameWithoutExtension(file),file);
                    cmbSymbolLib.Items.Insert(pos, item);
                    pos++;
                }

        }

        private string[] getXmalFiles()
        {
            string fullPathsymLib = (new FileInfo(this.GetType().Assembly.Location)).Directory.FullName + SymbolLibDir;
            if (Directory.Exists(fullPathsymLib))
                return Directory.GetFiles(fullPathsymLib, "*.xaml");

            return null;
        }

        private void cmbSymbolLib_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox symbolliblist = sender as ComboBox;
            if (symbolliblist != null)
            {
                object obj = symbolliblist.SelectedItem;
                if (obj is ComboBoxItem)
                {
                    switch((obj as ComboBoxItem).Tag.ToString())
                    {
                        case "sysSelect":break;
                        case "sysNew":createNewSymLib();break;
                        case "sysAppend":appendExistSymLib();break;
                        default:break;
                    }
                }
                if (obj is CustomItem)
                {
                    LoadResourceDictionary((obj as CustomItem).InnerText);
                }
            }
        }

        XamlSymbolResourceDictSerializer serializer = null;

        private void LoadResourceDictionary(string fileName)
        {
            try
            {
                MyGrid.Resources.Clear();
                //WebClient resClient = new WebClient();
                ////resClient.OpenReadCompleted += resClient_OpenReadCompleted;
                //Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
                ResourceDictionary rd = null;

                using (Stream s = new FileStream(fileName, FileMode.Open))
                {
                    //StreamReader re = new StreamReader(s);
                    //int i = 0;
                    //string bingo = null;
                    //string fulltext = re.ReadToEnd();
                    //re.BaseStream.Position = 0;
                    //while (i < 8)
                    //{
                    //    bingo = re.ReadLine();
                    //    i++;
                    //}

                    //int index = fulltext.IndexOf(bingo);
                    //System.Xaml.XamlXmlReader reader = new System.Xaml.XamlXmlReader(s);
                    //string ss = string.Empty;


                    //while (reader.Read())
                    //{ }

                    ////System.Xaml.XamlXmlWriter writer = new System.Xaml.XamlXmlWriter();

                    //string t = reader.ToString();

                    s.Position = 0;
                    //rd = XamlReader.Load(s) as ResourceDictionary;
                    //string tee=XamlWriter.Save(rd);
                    if (serializer != null)
                    {
                        serializer.Dispose();
                        serializer = null;
                    }
                    serializer = new XamlSymbolResourceDictSerializer(s);
                    rd = serializer.Read();
                    MyGrid.Resources = rd;
                    ResetSymbolDisplay();
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.ToString()); }
        }

        //void resClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        //{
        //    if (e.Error != null)
        //        return;

        //    ResourceDictionary rd = null;
        //    using (Stream s = e.Result)
        //    {
        //        rd = XamlReader.Load(s) as ResourceDictionary;
        //    }
        //    MyGrid.Resources = rd;
        //    MyGrid.Resources.Add("MyDictionaryConverter", new DictionaryConverter());
            
        //    ResetSymbolDisplay();
        //}


        private void ResetSymbolDisplay()
        {
            GraphicsLayer graphicsLayer = MyMap.Layers["SymbolViewer"] as GraphicsLayer;
            graphicsLayer.ClearGraphics();
            GraphicGenerator generator = new GraphicGenerator(MyGrid.Resources);
            generator.XamlSymbols = serializer.XamlSymbols;
            generator.GeneratorGraphics(MyMap.Extent, cmbSymbolLib.SelectedItem.ToString());
            generator.ViewInGraphicLayer(graphicsLayer);            
        }

        private void appendExistSymLib()
        {
            
        }

        private void createNewSymLib()
        {
            
        }

        private void GraphicsLayer_MouseEnter(object sender, GraphicMouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void GraphicsLayer_MouseLeave(object sender, GraphicMouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void GraphicsLayer_MouseLeftButtonDown(object sender, GraphicMouseButtonEventArgs e)
        {
            
            //tbSymbolID.Text = e.Graphic.Attributes["KEY"].ToString();
            //tbXaml.Text = e.Graphic.Attributes["XAML"].ToString();
        }

        private void btnAddNewSymbol_Click(object sender, RoutedEventArgs e)
        {

        }

        private Graphic currentGraphic = null;

        private void GraphicsLayer_MouseRightButtonDown(object sender, GraphicMouseButtonEventArgs e)
        {
            e.Graphic.Selected = !e.Graphic.Selected;
            currentGraphic = e.Graphic;
            graphicContextMenu.IsOpen = true;     
        }
    }
}
